//
//  FSBaseViewController.m
//  FSScrollViewNestTableViewDemo
//
//  Created by huim on 2017/5/23.
//  Copyright © 2017年 fengshun. All rights reserved.
//

#import "FSBaseViewController.h"
#import "FSBaseTableView.h"
#import "FSScrollContentView.h"
#import "FSScrollContentViewController.h"
#import "FSBottomTableViewCell.h"
#import "SVPullToRefresh.h"
#import "BHInfiniteScrollView.h"
#import "PS_AskViewController.h"
@interface FSBaseViewController ()<UITableViewDelegate,UITableViewDataSource,FSPageContentViewDelegate,FSSegmentTitleViewDelegate,BHInfiniteScrollViewDelegate>{
    
    UIView * scrollLine;
}
@property (nonatomic, strong) FSBaseTableView *tableView;
@property (nonatomic, strong) FSBottomTableViewCell *contentCell;
@property (nonatomic, strong) FSSegmentTitleView *titleView;
@property (nonatomic, strong) UIView * headerView;
@property (nonatomic , strong) BHInfiniteScrollView *infinitePageView;//上面的轮播
@property (nonatomic, assign) BOOL canScroll;
@end

@implementation FSBaseViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (UIView *)headerView{
    
    if (_headerView ==nil) {
        
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 175+SafeAreaTopHeight)];
        BHInfiniteScrollView *infinitePageView1 = [BHInfiniteScrollView infiniteScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,175+SafeAreaTopHeight) Delegate:self ImagesArray:@[] PlageHolderImage:[UIImage imageNamed:@"arror1"]];
        infinitePageView1.backgroundColor = [UIColor redColor];
        infinitePageView1.dotSize = 5;
        infinitePageView1.pageControlAlignmentOffset = CGSizeMake(0, 20);
        infinitePageView1.titleView.textColor = [UIColor whiteColor];
        infinitePageView1.titleView.margin = 30;
        infinitePageView1.titleView.hidden = YES;
        infinitePageView1.scrollTimeInterval = 4.5f;
        infinitePageView1.autoScrollToNextPage = YES;
        infinitePageView1.delegate = self;
        [infinitePageView1 setContentMode:UIViewContentModeScaleToFill];
        [_headerView addSubview:infinitePageView1];//头部广告栏
        _infinitePageView = infinitePageView1;
        
        
    }
    
    return _headerView;
}

- (void)loadSearchView{
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(15, 25, SCREEN_WIDTH-30-65-10, 35)];
    backView.layer.borderWidth = 1;
    backView.layer.borderColor = [UIColor whiteColor].CGColor;
    backView.layer.cornerRadius = 15;
    backView.backgroundColor = [UIColor whiteColor];
    backView.alpha = 0.5;
    [_headerView addSubview:backView];
    
    
    UITextField * searchTF =[[UITextField alloc]initWithFrame:CGRectMake(15, 25, SCREEN_WIDTH-30-65-10, 35)];
    searchTF.font = [UIFont systemFontOfSize:15];
    searchTF.textColor = [UIColor whiteColor];
    searchTF.layer.borderWidth = 1;
    searchTF.layer.borderColor = [UIColor whiteColor].CGColor;
    searchTF.layer.cornerRadius = 15;
    searchTF.backgroundColor = [UIColor clearColor];
    
    //文本框左视图
    UIView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    leftView.backgroundColor = [UIColor clearColor];
    
    UIImageView * searchLogo = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 20, 35)];
    searchLogo.image = [UIImage imageNamed:@"sousuo"];
    searchLogo.contentMode = UIViewContentModeScaleAspectFit;
    [leftView addSubview:searchLogo];
    searchTF.leftView = leftView;
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    
    NSString * placeholderStr = @" 请输入要查询的内容";
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:placeholderStr];
    [placeholder addAttribute:NSForegroundColorAttributeName
                        value:[UIColor whiteColor]
                        range:NSMakeRange(0, placeholderStr.length)];
    searchTF.attributedPlaceholder = placeholder;
    [_headerView addSubview:searchTF];
    
    UIButton * searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame = CGRectMake(CGRectGetMaxX(searchTF.frame)+10, 25, 65, 35);
    searchButton.layer.cornerRadius = 15;
    [searchButton setTitleColor:[UIColor colorWithHexString:@"EE726F"] forState:UIControlStateNormal];
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [searchButton setBackgroundColor:[UIColor whiteColor]];
    [searchButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:searchButton];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeScrollStatus) name:@"leaveTop" object:nil];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupSubViews];
    
    self.view.backgroundColor = RGBCOLOR(238, 238, 238);
    
    [self loadSearchView];
    
    [self loadTiWen];
}

- (void)setupSubViews
{
    self.canScroll = YES;
    self.tableView.backgroundColor = [UIColor whiteColor];
    __weak typeof(self) weakSelf = self;
    [self.tableView addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];
}

- (void)insertRowAtTop
{
    NSArray *sortTitles = @[@"推荐",@"热门",@"问答",@"维权"];
    self.contentCell.currentTagStr = sortTitles[self.titleView.selectIndex];
    self.contentCell.isRefresh = YES;

    FSScrollContentViewController *vc =_contentCell.viewControllers[self.titleView.selectIndex];
//    vc.isRefresh =YES;
//    vc.currentPage =1;
//    vc.totalPage =1;
    vc.returnRefreshBlock = ^(BOOL isSuccess) {
        [self.tableView.pullToRefreshView stopAnimating];
    };
//    NSString *type=[NSString stringWithFormat:@"%ld",self.titleView.selectIndex+1];
//    [vc requestDataWithType:type];
}

#pragma mark notify
- (void)changeScrollStatus//改变主视图的状态
{
    self.canScroll = YES;
    self.contentCell.cellCanScroll = NO;
}

#pragma mark UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return SCREEN_HEIGHT-kTabBarHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.titleView = [[FSSegmentTitleView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 50) titles:@[@"推荐",@"热门",@"回答",@"维权"] delegate:self indicatorType:FSIndicatorTypeEqualTitle];
    self.titleView.backgroundColor = [UIColor whiteColor];
    
    scrollLine = [[UIView alloc]initWithFrame:CGRectMake(15,47,(SCREEN_WIDTH-120)/4, 2)];
    scrollLine.backgroundColor = [UIColor colorWithHexString:@"f7bdcb"];
    [self.titleView addSubview:scrollLine];
    
    UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, 49, SCREEN_WIDTH, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"efefef"];
    [self.titleView addSubview:line];
    return self.titleView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    _contentCell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!_contentCell) {
        _contentCell = [[FSBottomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        NSArray *titles = @[@"推荐",@"热门",@"问答",@"维权"];
        NSMutableArray *contentVCs = [NSMutableArray array];
        for (NSString *title in titles) {
            FSScrollContentViewController *vc = [[FSScrollContentViewController alloc]init];
            vc.title = title;
            vc.str = title;
            NSString *type=nil;
            if ([title isEqualToString:@"推荐"]) {
                
                type =@"1";
                
            }else if ([title isEqualToString:@"热门"]){
                type =@"2";
            }else if ([title isEqualToString:@"问答"]){
                type =@"3";
            }else if ([title isEqualToString:@"维权"]){
                type =@"4";
            }
            vc.currentPage =1;
            vc.totalPage =1;
            [vc requestDataWithType:type];
            [contentVCs addObject:vc];
        }
        _contentCell.viewControllers = contentVCs;
        _contentCell.pageContentView = [[FSPageContentView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-kTabBarHeight) childVCs:contentVCs parentVC:self delegate:self];
        [_contentCell.contentView addSubview:_contentCell.pageContentView];
    }
    return _contentCell;
}

#pragma mark FSSegmentTitleViewDelegate
- (void)FSContenViewDidEndDecelerating:(FSPageContentView *)contentView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    self.titleView.selectIndex = endIndex;
    _tableView.scrollEnabled = YES;//此处其实是监测scrollview滚动，pageView滚动结束主tableview可以滑动，或者通过手势监听或者kvo，这里只是提供一种实现方式

}

- (void)FSSegmentTitleView:(FSSegmentTitleView *)titleView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    self.contentCell.pageContentView.contentViewCurrentIndex = endIndex;
     scrollLine.frame = CGRectMake(SCREEN_WIDTH/4*endIndex+15,47,(SCREEN_WIDTH-120)/4, 2);
}

- (void)FSContentViewDidScroll:(FSPageContentView *)contentView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex progress:(CGFloat)progress
{
    _tableView.scrollEnabled = NO;//pageView开始滚动主tableview禁止滑动
}

#pragma mark UIScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat bottomCellOffset = [_tableView rectForSection:0].origin.y;
    if (scrollView.contentOffset.y >= bottomCellOffset) {
        scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
        if (self.canScroll) {
            self.canScroll = NO;
            self.contentCell.cellCanScroll = YES;
        }
    }else{
        if (!self.canScroll) {//子视图没到顶部
            scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
        }
    }
    self.tableView.showsVerticalScrollIndicator = _canScroll?YES:NO;
}

#pragma mark LazyLoad
- (FSBaseTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[FSBaseTableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), SCREEN_HEIGHT-kTabBarHeight-10) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.bounces = NO;
        _tableView.tableHeaderView = self.headerView;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (void)loadTiWen{
    
    UIButton * askButton = [UIButton buttonWithType:UIButtonTypeCustom];
    askButton.frame = CGRectMake(SCREEN_WIDTH - 80-25, SCREEN_HEIGHT - 80-49-30,80,80);
    [askButton setBackgroundImage:[UIImage imageNamed:@"xuancengtiwen"] forState:UIControlStateNormal];
    [askButton addTarget:self action:@selector(askAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:askButton];
}
- (void)askAction:(UIButton *)sender{
    
    PS_AskViewController * VC = [[PS_AskViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
}
@end
